import os, sys, subprocess, argparse, shutil

from config import app 

parser = argparse.ArgumentParser(prog='AppInstaller', description='A basic tool for automating the installation and removal of an app')
parser.add_argument('--install', action='store_true')
parser.add_argument('--remove', action='store_true')
# parser.add_argument('--upgrade', action='store_true')
args = parser.parse_args()

def main():
    is_installed = False
    installed_version = None

    print(f'Welcome to the setup for {app["name"]["long"]}')
    if os.path.exists(f'/opt/{app["home"]}'):
        is_installed = True
        if os.path.exists(f'/opt/{app["home"]}/VERSION.txt'):
            with open(f'/opt/{app["home"]}/VERSION.txt') as f:
                installed_version = f.read().split('\n')[0]
                f.close()
        else:
            raise FileNotFoundError("VERSION.txt not found")
    if is_installed and installed_version:
        print(f'Current installation version: {installed_version}')
    if not is_installed and not installed_version:
        if args.remove:
            print('Arguement \'remove\' requires an existing installation')
            sys.exit(1)
        # if args.upgrade:
        #     print('Arguement \'upgrade\' requires an existing installation')
        #     sys.exit(1)
    if args.install:
        if not is_installed and not installed_version:
            subprocess.run(["python3", "-m", "PyInstaller", "--noconfirm", "--onedir", "--windowed", "--name", app["name"]["short"], "./main.py"])
            print('Built app from source')
            shutil.copytree(f'./dist/{app["name"]["short"]}', f'/opt/{app["home"]}')
            print(f'Copied app files to /opt/{app["home"]}')
            with open(f'/opt/{app["home"]}/VERSION.txt', 'w') as f:
                f.write(app['version'])
                f.close()
            print(f'Wrote app version to file at /opt/{app["home"]}/VERSION.txt')
            shutil.copy('./icon.png', f'/opt/{app["home"]}/icon.png')
            print(f'Copied app icon to /opt/{app["home"]}/icon.png')
            os.symlink(f'/opt/{app["home"]}/{app["name"]["short"]}', f'/usr/bin/{app["command"]}')
            print(f'Created symbolic link to app executable at /usr/bin/{app["command"]} to make app usable as a command')
            with open(f'/usr/share/applications/{app["home"]}.desktop', 'a') as f:
                f.write('[Desktop Entry]\n')
                f.write(f'Name={app["name"]["long"]}\n')
                f.write(f'Comment={app["description"]}\n')
                f.write(f'Exec=/opt/{app["home"]}/{app["name"]["short"]}\n')
                f.write('Terminal=false\n')
                f.write('Type=Application\n')
                f.write(f'Icon=/opt/{app["home"]}/icon.png')
                f.close()
            print('Created desktop entry at  to make app visible in applications list')
        else:
            print(f'{app["name"]["long"]} is already installed')
    elif args.remove:
        if os.path.exists(f'/usr/bin/{app["command"]}'):
            os.unlink(f'/usr/bin/{app["command"]}')
            print(f'Removed symbolic link at /usr/bin/{app["command"]} to make app no longer usable as a command')
        if os.path.exists(f'/opt/{app["home"]}'):
            shutil.rmtree(f'/opt/{app["home"]}')
            print(f'Removed app files at /opt/{app["home"]}')
        if os.path.exists(f'/usr/share/applications/{app["home"]}.desktop'):
            os.remove(f'/usr/share/applications/{app["home"]}.desktop')
            print(f'Removed desktop at /usr/share/applications/{app["home"]}.desktop to make app no longer visible in application list')
    # elif args.upgrade:
    #     pass
    else:
        print('No arguements')
        sys.exit(1)

if os.name == 'posix':
    if not os.environ.get("SUDO_UID") and os.geteuid() != 0:
        raise PermissionError("You need to run this script with sudo or as root.")
    main()
else:
    raise ValueError('It looks like you\'re not running this on Linux')
